﻿@using System.Web.Script.Serialization
@using eCommerce.Core.Domain.Messges

@{
    ViewBag.Title = "Create";
}


@{
    var model = ViewBag.Model;

    var jsonStr = new HtmlString(new JavaScriptSerializer().Serialize(model));
}




@Styles.Render("~/content/fineuploader/fineuploader-3.5.0.css")
@Scripts.Render("~/content/fineuploader/fineuploader-3.5.0.js")
@Scripts.Render("~/content/fineuploader/iframe.xss.response-3.5.0.js")


<div>
    <label>Product name</label>
    <input type="text" data-bind="value:ProductName" />
    <p data-bind="validationMessage: ProductName" class="text-error"></p>

    <div style="display: none">
        <label>Short Description</label>
        <textarea data-bind="value:ShortDescription" rows="10" class="input-xxlarge"></textarea>
        <p data-bind="validationMessage: ShortDescription" class="text-error"></p>
    </div>


    <label>Description</label>
    <textarea data-bind="value:FullDescription" rows="10" class="input-xxlarge" id="FullDescription"></textarea>
    <p data-bind="validationMessage: FullDescription" class="text-error"></p>
    

    <label>Stock Quantity</label>
    <input type="text" data-bind="value:StockQuantity" />
    <p data-bind="validationMessage: StockQuantity" class="text-error "></p>


    <label>Price</label>
    <input type="text" data-bind="value:Price" />
    <p data-bind="validationMessage: Price" class="text-error "></p>


    <label>Picture</label>
    <img data-bind="attr:{src: PictureUrl}" />
    <p data-bind="validationMessage: PictureId" class="text-error "></p>

    <ul id="manualUploadModeExample" class="unstyled"></ul>
  
    <input type="checkbox" data-bind="checked: UseProductAttributeKey"> use product attribute
    <div data-bind="visible:UseProductAttributeKey">
        <select name="productAttributeKeyName" data-bind="options: ProductAttributeKeys, optionsText: 'Name', value: ProductAttributeKeyId, optionsValue:'Id'"></select>
    </div>
    
    <div data-bind="visible:UseProductAttributeKey">
        <input type="checkbox" data-bind="checked: UseItemAttributeKey"> use item attribute
    </div>
    <div data-bind="visible:UseProductAttributeKey() == true && UseItemAttributeKey()==true">
        <select name="itemAttributeKeyName" data-bind="options: ItemAttributeKeys, optionsText: 'Name', value: ItemAttributeKeyId, optionsValue:'Id'"></select>
    </div>

    <input type="button" data-bind="value:'@T(MessageName.InsertProduct)', click:SaveProductInfo" class="btn btn-primary" />

</div>



@section scripts{



    @Scripts.Render("~/content/editor/tinymce/tinymce.js")


    <script>
        var init = @jsonStr;


        //function ProductAttributeKeyNameModel(keyName) {
        //    var self = this;
        //    self.KeyName = ko.observable(keyName);
        //}

        function ProductModel() {
            var self = this;
            self.Id = ko.observable(init.Id);

            self.ShopId = ko.observable(init.ShopId);

            self.ProductName = ko.observable(init.ProductName).extend({
                required: { message: '@T("Admin.Product.NeedProductName")' },
                maxLength: 400
            });

            self.ShortDescription = ko.observable(init.ShortDescription);

            self.FullDescription = ko.observable(init.FullDescription).extend({
                required: { message: '@T("Admin.Product.NeedFullDescription")' },
            });

            self.StockQuantity = ko.observable(init.StockQuantity).extend({
                required: { message: '@T("Admin.ProductVariant.NeedStockQuantity")' },
                digit: { message: '@T("Admin.ProductVariant.StockQuantityFormatError")' }
            });

            self.Price = ko.observable(init.Price).extend({
                required: { message: '@T("Admin.ProductVariant.NeedPrice")' },
                number: { message: '@T("Admin.ProductVariant.PriceFormatError")' }
            });

            self.ProductAttributeKeyId=ko.observable('');
            self.ItemAttributeKeyId=ko.observable('');

            self.UseProductAttributeKey = ko.observable(true);
            self.UseItemAttributeKey = ko.observable(true);

            self.ProductAttributeKeys = ko.observableArray(init.ProductAttributeKeys);
            self.ItemAttributeKeys = ko.observableArray(init.ItemAttributeKeys);

            self.PictureId = ko.observable(init.PictureId).extend({
                notEqual: { message: '@T("Admin.ProductVariant.NeedPicture")', params: 0 }
            });

            self.CategoryId = ko.observable(init.CategoryId);
            self.BrandId= ko.observable(init.BrandId);
            self.PictureIds = ko.observableArray([]);
            self.PictureUrl = ko.observable(init.PicUrl);

            self.ErrorMessage = ko.observable(null);
            self.SaveProductInfo = function() {
              
                
                self.FullDescription(tinyMCE.activeEditor.getContent());

                if (this.isValid()) {

                    self.PictureIds.push(self.PictureId);

                    $.ajax({
                        url: "/api/ProductApi/InsertProductInfo",
                        type: 'post',
                        data: ko.toJSON(self),
                        contentType: 'application/json',
                        success: function(result) {

                            if (result.Status == "0") {

//                            alert("保存成功");
                                location.href = '/Products/createitem?productId=' + result.Id;
                            } else {
                                // alert("保存失败：" + result.Msg);

                                toastr.error(result.Message);
                            }
                        }
                    });
                } else {

                    self.errors.showAllMessages();
                }


            };

        }

        var vm = new ProductModel();
        vm.errors = ko.validation.group(vm);
        ko.applyBindings(vm);

    </script>
    <script type="text/javascript">

        //Notes: autosave plugin is disabled
        (function() {

            tinyMCE.init({
                width: 544,
                selector: "#FullDescription",

                verify_html: false,
                plugins: [
                    "advlist autolink lists link image charmap print preview anchor",
                    "searchreplace visualblocks code fullscreen",
                    "insertdatetime media table contextmenu paste jbimages"
                ],
                toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image jbimages",
            });

        })();

        $(document).ready(function() {

            var errorHandler = function(event, id, fileName, reason) {
                qq.log("id: " + id + ", fileName: " + fileName + ", reason: " + reason);
            };


            var uploader2 = new qq.FineUploader({
                element: $('#manualUploadModeExample')[0],
                autoUpload: true,
                uploadButtonText: "Select Files",
                request: {
                    endpoint: "/FineUploader/UploadFile",
                    params: { "extraParam1": "true", "picSize": "100" }
                },
                callbacks: {
                    onError: errorHandler,
                    onComplete: function(id, fileName, responseJSON) {
                        if (responseJSON.success) {
                            vm.PictureId(responseJSON.OriginalPictureId);
                            vm.PictureUrl(responseJSON.NewPictureUrl);
                        }
                    }
                }
            });
        });

    </script>


}